using UFrame.Setting;
using UFrame.DataStore;
using UnityEngine;
using System;

public class SettingAgent : AgentContext<SettingAgent, ISettingCtrl>, UFrame.ILateUpdate
{
    private PreferSettingCtrl m_preferSetting;
    private LocalStoreSettingCtrl m_localStoreSetting;
    private int m_settingMode = 0;
    private float m_storeTimeSpan = 10;
    private string m_settingKey = "setting";
    private bool m_inited;
    public bool Runing => m_inited;
    public float Interval
    {
        get
        {
            return m_storeTimeSpan;
        }
        set { m_storeTimeSpan = value; }
    }
    public ref string SettingKey => ref m_settingKey;
    public ref float StoreTimeSpan => ref m_storeTimeSpan;
    protected override object ManageBody => this;

    protected override ISettingCtrl CreateAgent()
    {
        if (m_agent == null)
        {
            switch (m_settingMode)
            {
                case 1:
                    if (m_localStoreSetting == null)
                    {
                        CreateLocalStoreSettingCtrl();
                    }
                    m_agent = m_localStoreSetting;
                    break;
                default:
                    if (m_preferSetting == null)
                    {
                        CreatePreferSettingCtrl();
                    }
                    m_agent = m_preferSetting;
                    break;
            }
        }
        m_inited = true;
        m_agent.onSave = OnDataSaveOk;
        return m_agent;
    }

    private void OnDataSaveOk()
    {
        Debug.Log("data saved!");
    }

    private void CreateLocalStoreSettingCtrl()
    {
        m_localStoreSetting = new LocalStoreSettingCtrl();
        m_localStoreSetting.Initialize(m_settingKey);
    }

    private void CreatePreferSettingCtrl()
    {
        m_preferSetting = new PreferSettingCtrl();
        m_preferSetting.Initialize(m_settingKey);
    }

    public static void StartPreferSetting()
    {
        Context.m_settingMode = 0;
    }

    public static void StartLocalStoreSetting()
    {
        Context.m_settingMode = 1;
    }

    public void OnLateUpdate()
    {
        if (Instance != null)
        {
            Instance.FlashChange();
        }
    }
}
